﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LoRel
{

    public class BucketTransaction
    {
        public BucketTransaction(Key key, int bucket_count) { 
            m_Key = key; 
            m_CompletedBuckets = new IndexBucket[bucket_count];
            m_CompletionCount = 0;
            m_IsComplete = false;
        }
        
        private readonly Key m_Key;
        private readonly IndexBucket[] m_CompletedBuckets;
        private int m_CompletionCount;
        private bool m_IsComplete;

        public void ReceiveCompleteBucket(int bucket_index, IndexBucket bucket) {
            if( m_CompletedBuckets[bucket_index] != null ) throw new ArgumentException("Received the same index twice");
            m_CompletedBuckets[ bucket_index ] = bucket;
            m_CompletionCount++;
            if( m_CompletionCount == m_CompletedBuckets.Length ) {
                m_IsComplete = true;
                if (BucketComplete != null ) BucketComplete(this);
            }
        }

        public IndexBucket this[int index] { get { return m_CompletedBuckets[ index ]; } }
        public int Count { get { return m_CompletedBuckets.Length; } }
        public IEnumerable<IndexBucket> Items { get { return m_CompletedBuckets; } } 
        public event Action<BucketTransaction> BucketComplete;
        public bool IsComplete { get { return m_IsComplete; } }
        #region equality
        public bool Equals(BucketTransaction other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.m_Key, m_Key);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof(BucketTransaction)) return false;
            return Equals((BucketTransaction)obj);
        }

        public override int GetHashCode()
        {
            return (m_Key != null ? m_Key.GetHashCode() : 0);
        }

        #endregion
    }
}
